/**
 * WeeShop 声明
 * ===========================================================
 * 网站： https://www.darlang.com
 * 标题： ECShop 小程序「weeshop 」- 基于 ECShop 为后台系统开发的非官方微信商城小程序
 * 链接： https://www.darlang.com/?p=709
 * 说明： 源码已开源并遵循 Apache 2.0 协议，你有权利进行任何修改，但请保留出处，请不要删除该注释。
 * ==========================================================
 * Copyright 2019 darlang
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ===========================================================
 */

// add.js
import {PNT,setNavBarTitle,showToast} from '../../../../utils/utils';
import {AaddCommentDetail,AddOrderComment} from '../../../../utils/apis';

Page({
  /**
   * 页面的初始数据
   */
  data: {
    orderId: '',
    reviewsParams: [{
      goods: '',// 商品id
      grade: '',// 3好评 2中评 1差评
      content: '',// 评论内容
    }],
    isAnonymous: 1,// 是否匿名 1不匿名 0匿名
    orderInfo: '',
    goodsLst: '',
    star:[1,1,1,1,1],
    images:[],
    flag:true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (opt) {
    setNavBarTitle(PNT.comments.add);
    this.loginModal = this.selectComponent("#login-modal");

    if (!opt.id) {
      showToast('评论异常','error');
      return false;
    }
    var info = wx.getStorageSync('userInfo')

    this.setData({
      rec_id: opt.id,
      info:info,
    });
    console.log(opt)
    this.getOrderInfo();
  },

  /**
   * 登录回调
   * @author darlang
   */
  loginCallback(cb) {
    if (cb.detail.type === 'success') {
      this.getOrderInfo();
    }
  },

  /**
   * 输入
   * @author darlang
   */
  bindInputChange(e) {
    let items = e.currentTarget.dataset;
    let type = items.type;
    let v = e.detail.value || '';
    // let rp = this.data.reviewsParams;
    let g = this.data.goodsLst;

    if (type === 'star') {
      let grade = 0;
      if (items.star < 3) {
        grade = 1;
      }else if (items.star == 3) {
        grade = 2;
      }else {
        grade = 3;
      }
      g[items.i].grade = grade;
      g[items.i].star = items.star;
      g[items.i].goods = items.id;
      this.setData({
        goodsLst: g
      });
    }

    if (type ==='comment') {
      g[items.i].content = v;
      this.setData({
        goodsLst: g
      });
    }

    if (type === 'anonymous') {
      v = v ? 0 : 1;
      this.setData({
        isAnonymous: v
      });
    }
  },

  /**
   * 获取订单信息
   * @author darlang
   */
  getOrderInfo() {
    AaddCommentDetail(this.data.info.user_id,this.data.rec_id).then(res => {
      console.log(res)
      this.setData({
        goods:res.data,
      });
    });
  },

  changestar:function(e){
    var that = this;
    var id = e.currentTarget.dataset.type;
    var star = this.data.star;
    if(star[id]){
      for(var i = star.length-1;i>0;i--){
        if(star[i]){
          star[i] = 0;
          that.setData({
            star: star
          })
          return;
        }
      }
    }else{
      for(var i = 0;i<star.length;i++){
        if(!star[i]){
          star[i] = 1;
          that.setData({
            star: star
          })
          return;
        }
      }
    }

  },

  /**
   * 提交评论
   * @author darlang
   */
  submitReview() {
    let params = this.data.reviewsParams;
    let g = this.data.goodsLst;
    params = g.map(k => { return {goods: k.id, grade: k.grade, content: k.content};});
    params = JSON.stringify(params);
    wx.showLoading({title: '正在提交...',mask: true});
    AddOrderComment(this.data.orderId,params,this.data.isAnonymous).then(() => {
      showToast('评论成功','success',700);
      setTimeout(() => {
        wx.switchTab({
          url: '/pages/member/index/index',
        });
      }, 800);
    });
  },

  keywords:function(e){
    console.log(e)
    this.setData({
      keywords:e.detail.value
    })
  },

  submit:function(e){
    var that = this;
    var flag = this.data.flag;
    if(!this.data.flag){
      wx.showToast({
        title: '数据提交中...',
        icon:'none',
      })
      return;
    }
    flag = false;
    this.setData({
      flag:flag,
    })
    if(!this.data.keywords){
      wx.showToast({
        title: '请先输入评价',
        icon:'none'
      })
      that.setData({
        flag:true,
      })
      return;
    }
    var data = {};
    var key = this.data.keywords;
    data.key = key;
    var images = this.data.images;
    if(images.length>0){
      var img = "";
      for(var i = 0;i <images.length;i++){
        img +=images[i]+",";
      }
      data.img = img;
    }
    data.user_id = that.data.info.user_id;
    var rank = 0;
    var rank_data = that.data.star;
    for(var i= 0;i<rank_data.length;i++){
      rank = rank + rank_data[i]
    }
    data.rank = rank;
    data.rec_id = that.data.rec_id;

    AddOrderComment(data).then(res=>{
      console.log(res)
      if(res.error_code == 10000){
        wx.showToast({
          title: '添加成功',
        })
        setTimeout(function(){
          wx.switchTab({
            url: '/pages/member/index/index',
          })
        },2000)
      }
    }).catch(function(reason){
      wx.showToast({
        title: '系统繁忙',
        icon:'none'
      })
      that.setData({
        flag:true,
      })
    })


  },

  chooseimg:function(e){
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function(res) {
        console.log(res)
        var path = res.tempFilePaths[0]
        wx.uploadFile({
          url: 'https://www.donglongshangshi.com/wechatapi/index.php/wechatapi/index/comment_img', //仅为示例，非真实的接口地址
          filePath: path,
          name: 'file',
          formData: {
            'user_id': that.data.info.user_id
          },
          success(res) {
            var data= JSON.parse(res.data);
            if(data.error_code == 10000){
              var images = that.data.images;
              images.push(data.data);
              that.setData({
                images:images,
              })
              console.log(that.data.images)
            }
            //do something
          }
        })
      },
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
});